package org.tech4j.edi.schedule.common;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tech4j.edi.api.RetryRecordService;
import org.tech4j.edi.common.entity.RetryBizRecord;
import org.tech4j.edi.persistence.api.RetryRecordPersistService;
import org.tech4j.edi.persistence.api.query.RetryRecordScanQuery;
import org.tech4j.edi.schedule.common.entity.ScanEntity;

import java.util.List;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/10 15:49
 **/
public class DefaultScanRetryService implements ScanRetryService {
    private static final Logger log = LoggerFactory.getLogger(DefaultScanRetryService.class);

    private final RetryRecordService retryRecordService;
    private final RetryRecordPersistService retryRecordPersistService;

    public DefaultScanRetryService(RetryRecordService retryRecordService, RetryRecordPersistService retryRecordPersistService) {
        this.retryRecordService = retryRecordService;
        this.retryRecordPersistService = retryRecordPersistService;
    }

    @Override
    public void scanRetry(ScanEntity entity) {
        String retryMinId = retryRecordPersistService.getRetryMinId(entity.getEnv(), null, null);
        if (StringUtils.isBlank(retryMinId) || StringUtils.equals("0", retryMinId)) {
            log.info("Do scan retry [{}_{}] record is empty", entity.getEnv(), entity.getExecuteDate());
            return;
        }
        String retryMaxId = retryRecordPersistService.getRetryMaxId(entity.getEnv(), null, null);
        retryMinId = String.valueOf(Long.parseLong(retryMinId) - 1);
        while (true) {
            RetryRecordScanQuery query = RetryRecordScanQuery.Builder.builder()
                    .maxQuerySize(entity.getMaxScanSize())
                    .minId(retryMinId)
                    .maxId(retryMaxId)
                    .build();
            List<RetryBizRecord> retryBizRecords = retryRecordPersistService.scanRetryBizRecord(query);
            if (CollectionUtils.isEmpty(retryBizRecords)) {
                break;
            }
            retryMinId = retryBizRecords.get(retryBizRecords.size() - 1).getId();
            retryRecordService.retry(retryBizRecords);
        }
    }
}
